<template>
  <div>
    <h2>验证码</h2>
    <hr />
    <van-form @submit="onSubmit">
      <van-field
        v-model="phone"
        name="手机号"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请填写手机号' },
          { pattern: /^1[356789]\d{9}$/, message: '手机号格式错误' },
        ]"
      />
      <van-field
        v-model="sms"
        center
        clearable
        label="短信验证码"
        placeholder="请输入短信验证码"
        :rules="[{ required: true, message: '请填写验证码' }]"
      >
        <template #button>
          <van-button
            size="small"
            type="primary"
            @click.stop="sendCode()"
            :disabled="isClick"
            >{{ time }}</van-button
          >
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit">登录</van-button><br />

        <div class="btn">
          <van-button round block type="info" @click="login()">手机密码登录</van-button
          ><br />
          <van-button round block type="info" @click="register()">免费注册</van-button>
        </div>
      </div>
    </van-form>
  </div>
</template>
<script>
import url from "../tools/url.js";
import { Toast } from "vant";
export default {
  name: "YanZheng",
  data() {
    return {
      phone: "",
      sms: "",
      isClick: false,
      time: "发送验证码",
    };
  },
  methods: {
    onSubmit() {
      var str = `phone=${this.phone}&code=${this.sms}`;

      this.axios.post(url.LOGIN, str).then((res) => {
        if (res.data.code == 200) {
          Toast(res.data.data.message);
          //把token存到浏览器
          sessionStorage.setItem("token", res.data.data.token);
          //把用户信息存入vuex
          this.$store.commit("save", res.data.data);
          //跳转至首页
          this.$router.push("/");
        } else {
          Toast(res.data.data.message);
        }
      });
    },
    sendCode() {
      if (/^1[356789]\d{9}$/.test(this.phone)) {
        //禁用按钮，设置倒计时
        this.isClick = true;
        var s = 60;
        var timer = setInterval(() => {
          s--;
          this.time = s + "秒";
          if (s < 1) {
            this.time = "重新发送";
            this.isClick = false;
            clearInterval(timer);
          }
        }, 1000);

        console.log("发送验证码");
        this.axios.get(url.GETCODE + "?phone=" + this.phone).then((res) => {
          if ((res.data.code = 200)) {
            this.sms = res.data.data;
            Toast(res.data.message);
          } else {
            Toast(res.data.message);
          }
        });
      } else {
        Toast("手机号格式有误");
      }
    },
    login() {
      this.$router.push("/Login");
    },
    register() {
      this.$router.push({
        path: "/Register",
      });
    },
  },
};
</script>
<style scoped>
h2 {
  margin-top: 40px;
}
.btn {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.btn button {
  width: 45%;
}
</style>
